﻿using System.Diagnostics;
using System.Windows.Forms;

namespace Raider.WinForms.Actions.Utils
{
    /// <summary>
    /// Defines some utility functions related to the WinForms controls.
    /// </summary>
    public static class ControlUtils
    {
        /// <summary>
        /// Finds active and focused control of specified type.
        /// </summary>
        /// <typeparam name="TControl">Type of the control to search for.</typeparam>
        /// <returns>Focused control reference, or <c>null</c>.</returns>
        public static TControl GetFocusedControl<TControl>(Form activeForm = null) where TControl : Control
        {
            return GetFocusedControl(activeForm) as TControl;
        }

        /// <summary>
        /// Finds current active and focused control.
        /// </summary>
        /// <returns>Focused control reference, or <c>null</c>.</returns>
        public static Control GetFocusedControl(Form activeForm = null)
        {
            Control activeControl = activeForm ?? Form.ActiveForm;

            var container = (ContainerControl)activeControl;
            while (container != null)
            {
                activeControl = container.ActiveControl;
                container = activeControl as ContainerControl;
            }

            return activeControl;
        }
    }
}
